package com.yanlin.apidriver.interceptor;

import com.yanlin.internalcommon.dto.ResponseResult;
import com.yanlin.internalcommon.dto.TokenResult;
import com.yanlin.internalcommon.util.JwtUtils;
import com.yanlin.internalcommon.util.RedisPrefixUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;

import static com.yanlin.internalcommon.constant.TokenConstant.ACCESS_TOKEN_TYPE;

/**
 * <p>标题：interceptor</p>
 * <p>功能：</p>
 * <p>
 * 其他说明：
 * </p>
 * <p>审核：</p>
 * <p>重构：</p>
 * <p>创建日期：2025-06-15 16:10</p>
 *
 * @author yanlin
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        boolean result = true;
        String resultString = null;
        String authorization = request.getHeader("authorization");
        TokenResult tokenResult = JwtUtils.checkToken(authorization);
        if (tokenResult == null) {
            result = false;
            resultString = "token invalid";
        } else {
            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();
            String accessTokenKey = RedisPrefixUtil.getTokenKey(phone, identity, ACCESS_TOKEN_TYPE);
            String accessTokenRedis = stringRedisTemplate.opsForValue().get(accessTokenKey);
            if(StringUtils.isBlank(accessTokenRedis)
                    || !StringUtils.equals(authorization, accessTokenRedis)) {
                result = false;
                resultString = "token invalid";
            }
        }
        if (!result) {
            // 结果写入响应
            JSONObject resultJson = JSONObject.fromObject(ResponseResult.fail(resultString));
            PrintWriter writer = response.getWriter();
            writer.print(resultJson.toString());
        }
        return result;
    }

}